package com.ypj.indusynergyems.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ypj.indusynergyems.dao.entity.CategoryEntity;
import com.ypj.indusynergyems.dao.mapper.CategoryMapper;
import com.ypj.indusynergyems.service.CategoryService;
import com.ypj.indusynergyems.web.Catalog2VO;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper,CategoryEntity> implements CategoryService {

    /**
     * 查出所有1级分类
     */
    @Override
    public List<CategoryEntity> getLevel1Categorys() {
        System.out.println("调用了getLevel1Categorys...");
        // 查询父id=0
        return baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid", 0));
    }
    @Override
    public Map<String,List<Catalog2VO>> getCatalogJson() {
        //1.查出所有一级分类
        List<CategoryEntity> level1Categorys = getLevel1Categorys();

        //2.封装数据
        Map<String,List<Catalog2VO>> parent_cid = level1Categorys.stream().collect(Collectors.toMap(k -> k.getCatId().toString(),v->{
            //1.每一个一级分类，查到这个一级分类的二级分类
            List<CategoryEntity> categoryEntities = baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid", v.getCatId()));
            //2.分装上面的结果
            List<Catalog2VO> catalog2VOS = null;
            if(categoryEntities!=null){
                catalog2VOS = categoryEntities.stream().map(l2->{
                    Catalog2VO catalog2VO = new Catalog2VO(v.getCatId().toString(),null,l2.getCatId().toString(),l2.getName());
                    //3.每一个二级分类，查到这个二级分类的三级分类
                    List<CategoryEntity> level3Catelog = baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid", l2.getCatId()));
                    if (level3Catelog!=null){
                        List<Catalog2VO.Catalog3Vo> collect = level3Catelog.stream().map(l3 -> {
                            //3.分装指定格式
                            Catalog2VO.Catalog3Vo catelog3Vo = new Catalog2VO.Catalog3Vo(l2.getCatId().toString(), l3.getCatId().toString(), l3.getName());
                            return catelog3Vo;
                        }).collect(Collectors.toList());
                        catalog2VO.setCatalog3List(collect);
                    }

                    return catalog2VO;
                }).collect(Collectors.toList());
            }

            return catalog2VOS;
        }));
        return parent_cid;
    }

    @Override
    public List<CategoryEntity> getLevel2Categorys() {
        return baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("cat_level", 2));
    }

    @Override
    public List<CategoryEntity> getLevel3Categorys() {
        return baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("cat_level", 3));
    }
}
